package com.cby.springboot.demo.service;

import com.cby.springboot.demo.bean.Book;
import com.cby.springboot.demo.bean.Category;
import com.cby.springboot.demo.mapper.BookMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("libraryService")
public class LibraryServiceImpl implements LibraryService{

    @Autowired
    BookMapper bookMapper;

    @Override
    public int updateBook(Book book) {
        return bookMapper.updateBook(book);
    }

    @Override
    public int addBook(Book book) {
        if(book.getCategory() != null) {
            Category category = book.getCategory();
            logI(category.toString());
            int addBookResult = bookMapper.addBook(book);
            int updateBook = bookMapper.updateBookForCId(book.getTitle(), book.getCategory().getId());
            return addBookResult + updateBook;
        }
        return bookMapper.addBook(book);
    }

    @Override
    public int deleteById(int id) {
        return bookMapper.deleteById(id);
    }

    @Override
    public List<Book> list() {
        return bookMapper.list();
    }

    @Override
    public List<Book> findAllByCategory(int id) {
        return bookMapper.findAllByCategory(id);
    }

    @Override
    public List<Book> findAllByTitleLikeOrAuthorLike(String keyword1, String keyword2) {
        return bookMapper.findAllByTitleLikeOrAuthorLike(keyword1, keyword2);
    }

    private Logger logger = null;

    public void initLogger() {
        logger = LoggerFactory.getLogger(this.getClass());
    }

    public void logI(String msg) {
        if(logger  == null) {
            initLogger();
        }
        logger.info(msg);
    }
}
